package com.sgj.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 演示线程池三种常用分类
 * @Author: Guoji Shen
 * @Date: 2021/8/10 16:17
 */
public class ThreadPoolDemo1 {
    public static void main(String[] args) {
        // 一池五线程
        // test1();

        // 一池一线程
        // test2();

        // 一池可扩容线程
        test3();
    }

    public static void test1() {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        exec(threadPool);
    }

    public static void test2() {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        exec(threadPool);
    }

    public static void test3() {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        exec(threadPool);
    }

    public static void exec(ExecutorService threadPool) {
        // 20个顾客请求
        try {
            for (int i = 1; i <= 20; i++) {
                // 执行
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " 正在办理业务");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            threadPool.shutdown();
        }
    }
}